﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Security;
using System.Data;
using System.Utility.DBMS;
using System.Utility.UI;
using System.Utility.Messaging;


namespace Logistics
{
    public partial class WebForm3 : System.Web.UI.Page
    {
        List<DateTime> selectedDates = new List<DateTime>();
        DataSet ds = new DataSet();

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!Page.IsPostBack)
            {
                DataSet ds = new DataSet();
                SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["DBConnString"].ToString());
                SqlCommand cmd = new SqlCommand("SP_RetrieveStore", cn);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                ddl1.DataSource = ds.Tables[0];
                ddl1.DataValueField = "Store_code";
                ddl1.DataTextField = "Store";
                ddl1.DataBind();


                

                int startyear = 2015;
                int currentyear = startyear + 1;
                for (int i = 2000; i < currentyear; i++)
                {
                    ddlYear.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                }


                string[] months = new string[] { "January", "Febraury", "March", "April", "May", "June", "July", "August", "September", "October", "November", "Decemeber" };

                for (int i = 0; i < months.Length; i++)
                {
                    ListItem monthItem1 = new ListItem();
                    monthItem1.Text = months[i];

                    monthItem1.Value = (i + 1).ToString();
                    ddlMonth.Items.Add(monthItem1);

                }

                DataRow row = ds.Tables[1].NewRow();
                row["Retail_Cat1"] = "All";
                ds.Tables[1].Rows.InsertAt(row, 0);
                //DataRow row1 = ds.Tables[2].NewRow();
                //row1["Retail_Cat1"] = "OTHER";
                //ds.Tables[2].Rows.InsertAt(row, 0);
                DataColumn col1 = new DataColumn("Retail_Cat1"); col1.DefaultValue = "All";
                DataSet retailDS = new DataSet();
                DataTable dt = new DataTable(); dt.Columns.Add(col1);
                DataRow dr = dt.NewRow();
                DataRow dr1 = dt.NewRow();

                //DataColumn col2 = new DataColumn("Retail_Cat1"); col2.DefaultValue = "Other";

                dr1[0] = "DETAIL";
                dt.Rows.Add(dr);
                dt.Rows.Add(dr1);
                retailDS.Tables.Add(dt);

                ddl2.DataSource = retailDS;//ds.Tables[1];
                ddl2.DataValueField = "Retail_Cat1";
                ddl2.DataTextField = "Retail_Cat1";
                ddl2.DataBind();


                if (Session["SelectesStore"] != null)
                    ddl1.SelectedValue = Session["SelectesStore"].ToString();

                DateTime currenttime = DateTime.Now;
                ddlYear.SelectedValue = currenttime.Year.ToString();
                ddlMonth.SelectedValue = (currenttime.Month - 1).ToString();

                BindUserPercents();
                selectedvalue();

            }

        }
        public void Transdateselectedvalue(Calendar cal)
        {


            //DataSet ds = new DataSet();
            //SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString());
            //SqlCommand cmd = new SqlCommand("Value_by_Transdate", cn);
            //cmd.CommandType = CommandType.StoredProcedure;

            //int j;
            //int.TryParse(ddl1.SelectedValue.ToString(), out j);

            //cmd.Parameters.Add("@arg_store_code", SqlDbType.Int).Value = j;
            //cmd.Parameters.Add("@arg_trans_date", SqlDbType.Int).Value = cal.SelectedDate;
            //cmd.Parameters.Add("@arg_cat_type", SqlDbType.Int).Value = ddl2.SelectedValue;
            //SqlDataAdapter da = new SqlDataAdapter(cmd);
            //da.Fill(ds);

            /*DataRow dr = ds.Tables[0].NewRow();
            dr[0] = "All";
            GetTotal(ds, dr);
            ds.Tables[0].Rows.Add(dr);
            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();*/

        }

        public void selectedvalue()
        {

            DataSet ds = new DataSet();
            SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["DBConnString"].ToString());
            //SqlCommand cmd = new SqlCommand("DBO.BPPCalculate", cn);
            SqlCommand cmd = new SqlCommand("DBO.testBPPCalculate", cn);

            cmd.CommandType = CommandType.StoredProcedure;

            //int j;
            //int.TryParse(ddl1.SelectedValue.Split(',')[0].ToString(), out j);
            cmd.Parameters.Add("@storecode", SqlDbType.VarChar).Value = ddl1.SelectedValue.Split(',')[0].ToString();
            cmd.Parameters.Add("@year", SqlDbType.Int).Value = ddlYear.SelectedValue;
            cmd.Parameters.Add("@month", SqlDbType.Int).Value = ddlMonth.SelectedValue;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);

            DataRow dr = ds.Tables[0].NewRow();
            dr[0] = "All";
            GetTotal(ds, dr);
            GetRentTotal(ds, dr);
            ds.Tables[0].Rows.Add(dr);
            if (!(ds.Tables[1] != null && ds.Tables[1].Rows.Count > 1))
            {
                GetAllRentTotal(ds);
            }
            //GetAllRentTotal(ds);
            GridView1.AutoGenerateColumns = false;
            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
            
            if (ds.Tables[1] != null && ds.Tables[1].Rows.Count > 0)
            {
                GridView2.Visible = true;
                GridView2.DataSource = ds.Tables[1];
                GridView2.DataBind();
            }
            else
            {
                GridView2.Visible = true;
                ds.Tables[1].Rows.Add(ds.Tables[1].NewRow());
                GridView2.DataSource = ds.Tables[1];
                GridView2.DataBind();

                GridView2.Rows[0].Cells.Clear();
                GridView2.Rows[0].Cells.Add(new TableCell());
                GridView2.Rows[0].Cells[0].ColumnSpan = 3;
                GridView2.Rows[0].Cells[0].Text = "No Records Found!";
                GridView2.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
                GridView2.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Red;
            
            }
            BindUserPercents();

        }
        private static void GetTotal(DataSet ds, DataRow dr)
        {
            decimal total = 0;
            if (ds.Tables[0].Rows.Count >= 1 && ds.Tables[0].Rows[0] != null)
            {
                total += (ds.Tables[0].Rows[0][1] == null ? 0 : Convert.ToDecimal(ds.Tables[0].Rows[0][1]));
            }
            if (ds.Tables[0].Rows.Count > 1 && ds.Tables[0].Rows[1] != null)
            {
                total += (ds.Tables[0].Rows[1][1] == null ? 0 : Convert.ToDecimal(ds.Tables[0].Rows[1][1]));

            }
            if (ds.Tables[0].Rows.Count > 2 && ds.Tables[0].Rows[2] != null)
            {
                total += (ds.Tables[0].Rows[2][1] == null ? 0 : Convert.ToDecimal(ds.Tables[0].Rows[2][1]));
            }
            dr[1] = total;
        }
        private static void GetAllRentTotal(DataSet ds)
        {
            decimal allRent = 0;
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                if (row[0].ToString().ToUpper() != "ALL")
                    if (row["rent"] != null && !string.IsNullOrEmpty(row["rent"].ToString()))
                    {
                        allRent = allRent + Convert.ToDecimal((row["Rent"] != null ? row["Rent"] : 0));
                    }
            }
            ds.Tables[0].Rows[ds.Tables[0].Rows.Count - 1]["Rent"] = allRent;
        }
        private void GetRentTotal(DataSet ds, DataRow dr)
        {
            decimal appRenttotal = 0;
            decimal acpRentTotal = 0;
            decimal otherRentTotal = 0;
            decimal allRentTotal = 0;
           // string allRentTotalString = string.Empty;
           // string appRenttotalString = string.Empty;
            //string acpRentTotalString = string.Empty;
          //  string otherRentTotalString = string.Empty;
            
            if (ds.Tables[2] != null && ds.Tables[2].Rows.Count >= 1)
            {
                for (int i = 0; i < ds.Tables[2].Rows.Count; i++)
                {
                    #region  ifblock

                    DateTime givenDate = new DateTime(Convert.ToInt16(ddlYear.SelectedValue), Convert.ToInt16(ddlMonth.SelectedValue), 1);
                    DateTime startDate = Convert.ToDateTime(ds.Tables[2].Rows[i]["StartDate"]).Date;
                    DateTime endDate = Convert.ToDateTime(ds.Tables[2].Rows[i]["EndDate"]).Date;
                    //if (endDate > givenDate && startDate < givenDate)
                    //{
                    //    startDate = givenDate.Date;
                    //}
                    //else
                    //{
                    //    endDate = givenDate.AddMonths(1).AddDays(-1).Date;
                    //    //new DateTime(Now.Year, Now.Month, 1).AddMonths(1).AddDays(-1)
                    //}
                    decimal perecent = Convert.ToDecimal(ds.Tables[2].Rows[i]["BPPercent"]);
                    SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["DBConnString"].ToString());
                    SqlCommand cmd = new SqlCommand("GetSumOfTotalByDates", cn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    DataSet ds1 = new DataSet();
                    int j;
                    int.TryParse(ddl1.SelectedValue.Split(',')[0].ToString().ToString(), out j);
                    // DateTime DT = cal.TodaysDate;
                    cmd.Parameters.Add("@StartDate", SqlDbType.DateTime).Value = startDate;
                    cmd.Parameters.Add("@EndDate", SqlDbType.DateTime).Value = endDate;
                    cmd.Parameters.Add("@Store_Code", SqlDbType.VarChar).Value = ddl1.SelectedValue;

                    cmd.Parameters.Add("@Retail_Cat1", SqlDbType.VarChar).Value = "APP";

                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(ds1);

                    appRenttotal = appRenttotal + (ds1.Tables[0].Rows[0]["Total"] != DBNull.Value ? Convert.ToDecimal(ds1.Tables[0].Rows[0]["Total"]) : 0) * perecent;

                    ds1 = new DataSet();
                    cmd.Parameters["@Retail_Cat1"].Value = "ACC";
                    da = new SqlDataAdapter(cmd);
                    da.Fill(ds1);

                    acpRentTotal = acpRentTotal + (ds1.Tables[0].Rows[0]["Total"] != DBNull.Value ? Convert.ToDecimal(ds1.Tables[0].Rows[0]["Total"]) : 0) * perecent;

                    ds1 = new DataSet();
                    cmd.Parameters["@Retail_Cat1"].Value = "OTHER";
                    da = new SqlDataAdapter(cmd);
                    da.Fill(ds1);

                    otherRentTotal = otherRentTotal + (ds1.Tables[0].Rows[0]["Total"] != DBNull.Value ? Convert.ToDecimal(ds1.Tables[0].Rows[0]["Total"]) : 0) * perecent;
                    //take storecode
                    //pass retail_cat1 as app
                    // call rent procedure
                    // take sum of amount, sum of amount * percent = rent

                    #endregion
                }
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    if (row["Retail_Cat1"].ToString() == "APP")
                    {
                        row[2] = decimal.Round(appRenttotal,2).ToString("#,###.##");
                    }
                    if (row["Retail_Cat1"].ToString() == "ACC")
                    {
                        row[2] = decimal.Round(acpRentTotal,2).ToString("#,###.##");
                    }
                    if (row["Retail_Cat1"].ToString() == "OTHER")
                    {
                        row[2] = decimal.Round(otherRentTotal,2).ToString("#,###.##");
                    }
                }
                allRentTotal = appRenttotal + acpRentTotal + otherRentTotal;
           //     allRentTotalString = allRentTotal.ToString("#.##");

            }
            else if (ds.Tables[2] != null && ds.Tables[2].Rows.Count >= 1)
            {
                DateTime startDate = Convert.ToDateTime(ds.Tables[2].Rows[0]["StartDate"]);
                DateTime endDate = Convert.ToDateTime(ds.Tables[2].Rows[0]["EndDate"]);
                decimal perecent = Convert.ToDecimal(ds.Tables[2].Rows[0]["BPPercent"]);

                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    var rent = Convert.ToDecimal(row["Total"]) * perecent;
                    row["Rent"] = rent;
                }
                //SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString());
                //SqlCommand cmd = new SqlCommand("GetSumOfTotalByDates", cn);
                //cmd.CommandType = CommandType.StoredProcedure;
                //DataSet ds1 = new DataSet();
                //int j;
                //int.TryParse(ddl1.SelectedValue.Split(',')[0].ToString().ToString(), out j);
                //// DateTime DT = cal.TodaysDate;
                //cmd.Parameters.Add("@StartDate", SqlDbType.DateTime).Value = startDate;
                //cmd.Parameters.Add("@EndDate", SqlDbType.DateTime).Value = endDate;
                //cmd.Parameters.Add("@Store_Code", SqlDbType.VarChar).Value = ddl1.SelectedValue;

                //cmd.Parameters.Add("@Retail_Cat1", SqlDbType.VarChar).Value = "APP";
            }
            //for (int k = 0; k < ds.Tables[0].Rows.Count; k++)
            //{
            //    for (int j = 0; j < ds.Tables[1].Rows.Count; j++)
            //    {
            //        for (int i = 0; i < DateTime.DaysInMonth(Convert.ToInt32(ddlYear.SelectedValue), Convert.ToInt32(ddlMonth.SelectedValue)); i++)
            //        {
            //            var dt = new DateTime(Convert.ToInt32(ddlYear.SelectedValue), Convert.ToInt32(ddlMonth.SelectedValue), i + 1);
            //            if (Convert.ToDateTime(ds.Tables[1].Rows[j]["StartDate"]) <= dt && Convert.ToDateTime(ds.Tables[1].Rows[j]["EndDate"]) >= dt)
            //            {
            //                double val = Math.Round(Convert.ToDouble(ds.Tables[0].Rows[k][1]) / DateTime.DaysInMonth(Convert.ToInt32(ddlYear.SelectedValue), Convert.ToInt32(ddlMonth.SelectedValue)),3);
            //                total += Math.Round(Convert.ToDecimal(val) *Convert.ToDecimal(ds.Tables[1].Rows[j]["BPPercent"]),2);
            //            }
            //        }
            //    }

            //    ds.Tables[0].Rows[k][2] = total;
            //    total = 0;
            //}
            //if (ds.Tables[0].Rows.Count >= 1 && ds.Tables[0].Rows[0] != null)
            //{
            //    total += (ds.Tables[0].Rows[0][2] == DBNull.Value ? 0 : Convert.ToDecimal(ds.Tables[0].Rows[0][2]));
            //}
            //if (ds.Tables[0].Rows.Count > 1 && ds.Tables[0].Rows[1] != null)
            //{
            //    total += (ds.Tables[0].Rows[1][2] == DBNull.Value ? 0 : Convert.ToDecimal(ds.Tables[0].Rows[1][2]));

            //}
            //if (ds.Tables[0].Rows.Count > 2 && ds.Tables[0].Rows[2] != null)
            //{
            //    total += (ds.Tables[0].Rows[2][2] == DBNull.Value ? 0 : Convert.ToDecimal(ds.Tables[0].Rows[2][2]));
            //}
            //dr[2] = decimal.Round(allRentTotal,2);
            dr[2] = decimal.Round(allRentTotal, 2).ToString("#,###.##");
        }
        //old code for calcuating monthly rent
       /* private static void GetTotal(DataSet ds, DataRow dr)
        {
            decimal total = 0;
            if (ds.Tables[0].Rows.Count >= 1 && ds.Tables[0].Rows[0] != null)
            {
                total += (ds.Tables[0].Rows[0][1] == null ? 0 : Convert.ToDecimal(ds.Tables[0].Rows[0][1]));
            }
            if (ds.Tables[0].Rows.Count > 1 && ds.Tables[0].Rows[1] != null)
            {
                total += (ds.Tables[0].Rows[1][1] == null ? 0 : Convert.ToDecimal(ds.Tables[0].Rows[1][1]));

            }
            if (ds.Tables[0].Rows.Count > 2 && ds.Tables[0].Rows[2] != null)
            {
                total += (ds.Tables[0].Rows[2][1] == null ? 0 : Convert.ToDecimal(ds.Tables[0].Rows[2][1]));
            }
            dr[1] = total;
        }
        private void GetRentTotal(DataSet ds, DataRow dr)
        {
            decimal total = 0;
            for (int k = 0; k < ds.Tables[0].Rows.Count; k++)
            {
                for (int j = 0; j < ds.Tables[1].Rows.Count; j++)
                {
                    for (int i = 0; i < DateTime.DaysInMonth(Convert.ToInt32(ddlYear.SelectedValue), Convert.ToInt32(ddlMonth.SelectedValue)); i++)
                    {
                        var dt = new DateTime(Convert.ToInt32(ddlYear.SelectedValue), Convert.ToInt32(ddlMonth.SelectedValue), i + 1);
                        if (Convert.ToDateTime(ds.Tables[1].Rows[j]["StartDate"]) <= dt && Convert.ToDateTime(ds.Tables[1].Rows[j]["EndDate"]) >= dt)
                        {
                            double val = Math.Round(Convert.ToDouble(ds.Tables[0].Rows[k][1]) / DateTime.DaysInMonth(Convert.ToInt32(ddlYear.SelectedValue), Convert.ToInt32(ddlMonth.SelectedValue)), 3);
                            total += Math.Round(Convert.ToDecimal(val) * Convert.ToDecimal(ds.Tables[1].Rows[j]["BPPercent"]), 2);
                        }
                    }
                }

                ds.Tables[0].Rows[k][2] = total;
                total = 0;
            }
            if (ds.Tables[0].Rows.Count >= 1 && ds.Tables[0].Rows[0] != null)
            {
                total += (ds.Tables[0].Rows[0][2] == DBNull.Value ? 0 : Convert.ToDecimal(ds.Tables[0].Rows[0][2]));
            }
            if (ds.Tables[0].Rows.Count > 1 && ds.Tables[0].Rows[1] != null)
            {
                total += (ds.Tables[0].Rows[1][2] == DBNull.Value ? 0 : Convert.ToDecimal(ds.Tables[0].Rows[1][2]));

            }
            if (ds.Tables[0].Rows.Count > 2 && ds.Tables[0].Rows[2] != null)
            {
                total += (ds.Tables[0].Rows[2][2] == DBNull.Value ? 0 : Convert.ToDecimal(ds.Tables[0].Rows[2][2]));
            }
            dr[2] = total;
        }*/
        protected void ddl2_SelectedIndexChanged(object sender, EventArgs e)
        {
            //OutlookCalendar.DayRender();
        }

        //protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
        //{

        //}


        protected void ListView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        protected void SelectionModeCalendar_SelectionChanged(object sender, EventArgs e)
        {


            selectedDates.Add(((Calendar)sender).SelectedDate);
            Calendar cal = new Calendar();


        }

        protected void OutlookCalendar_DayRender(object sender, DayRenderEventArgs e)
        {

            //if (selectedDates.Count > 0 &&  selectedDates[0].Date == e.Day.Date)//selectedDates.Count > 0 && selectedDates.FirstOrDefault(x => x.Day == e.Day.Date.Day) != null)
            {
                //if (e.Day.IsOtherMonth)
                //{
                //    e.Cell.Text = string.Empty;
                //}
                SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["DBConnString"].ToString());
                SqlCommand cmd = new SqlCommand("Value_by_Transdate", cn);
                cmd.CommandType = CommandType.StoredProcedure;
                DataSet ds = new DataSet();
                int j;
                int.TryParse(ddl1.SelectedValue.ToString(), out j);
                // DateTime DT = cal.TodaysDate;
                cmd.Parameters.Add("@arg_store_code", SqlDbType.Int).Value = j;
                cmd.Parameters.Add("@arg_trans_date", SqlDbType.DateTime).Value = e.Day.Date;
                cmd.Parameters.Add("@arg_cat_type", SqlDbType.VarChar).Value = ddl2.SelectedValue;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                Table tbl = new Table();
                var selectedDrpDwnval = ddl2.SelectedValue;
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    TableRow tr = new TableRow();
                    TableCell tc = new TableCell();
                    if (dr["Column1"].ToString().ToUpper() == selectedDrpDwnval.ToUpper() && selectedDrpDwnval.ToUpper() == "ALL")
                    {
                        Label lblCat = new Label();
                        lblCat.Text = dr["Column1"] + ":";
                        lblCat.CssClass = "cal-text-left";
                        Label lblVal = new Label();
                        lblVal.Text = string.Format("{0:N}", dr["Column2"]);
                        lblVal.CssClass = "cal-text-right";
                        tc.Controls.Add(lblCat);
                        tc.Controls.Add(lblVal);
                        //tc.Text = dr["Column1"] + ":" + dr["Column2"];
                       // tc.Text = dr["Column1"] + ":" + string.Format("{0:N}", dr["Column2"]);
                        tr.Cells.Add(tc); tbl.Rows.Add(tr);
                    }
                    else if (selectedDrpDwnval.ToUpper() == "DETAIL")
                    {
                        if (dr["Column1"].ToString().ToUpper() != "ALL")
                        {
                            Label lblCat = new Label();
                            lblCat.Text = dr["Column1"] + ":";
                            lblCat.CssClass = "cal-text-left";
                            Label lblVal = new Label();
                            lblVal.Text = string.Format("{0:N}", dr["Column2"]);
                            lblVal.CssClass = "cal-text-right";
                            tc.Controls.Add(lblCat);
                            tc.Controls.Add(lblVal);
                            //tc.Text = dr["Column1"] + ":" + dr["Column2"];
                            //tc.Text = dr["Column1"] + ":" + string.Format("{0:N}", dr["Column2"]);
                            tr.Cells.Add(tc); tbl.Rows.Add(tr);
                        }
                    }

                    // tc.Text = dr[]

                }


                //Literal lineBreak = new Literal();
                //lineBreak.Text = "<br />";

                e.Cell.Controls.Add(tbl);
            }
            // OutlookCalendar.SelectedDate = DateTime.MinValue;

        }
        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            selectedvalue();
            OutlookCalendar.VisibleDate = new DateTime(Convert.ToInt32(ddlYear.SelectedValue), Convert.ToInt32(ddlMonth.SelectedValue), 1);
        }

        protected void GridView1_SelectedIndexChanged1(object sender, EventArgs e)
        {

        }

        protected void GetSummary(object sender, EventArgs e)
        {
            selectedvalue();
            OutlookCalendar.VisibleDate = new DateTime(Convert.ToInt32(ddlYear.SelectedValue), Convert.ToInt32(ddlMonth.SelectedValue), 1);
        }

        protected void GridView1_SelectedIndexChanged2(object sender, EventArgs e)
        {

        }

        protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "AddNew")
                {
                    TextBox txtFromDate = (TextBox)gridUserPercents.FooterRow.FindControl("txtFromDate");
                    TextBox txtEndDate = (TextBox)gridUserPercents.FooterRow.FindControl("txtEndDate");
                    DropDownList ddlCategory = (DropDownList)gridUserPercents.FooterRow.FindControl("ddlCategory");
                    TextBox txtUPercent = (TextBox)gridUserPercents.FooterRow.FindControl("txtUPercent");
                    TextBox txtComments = (TextBox)gridUserPercents.FooterRow.FindControl("txtComments");
                
                

                DBHelper.Add("AddSPPercent", new object[] { 
            txtFromDate.Text,
            txtEndDate.Text,
            "0."+txtUPercent.Text,
            txtComments.Text,
            ddlCategory.SelectedItem.ToString(),
            1,
            ddl1.SelectedValue.Split(',')[0].ToString()
            });
                PageUtility.RegisterClientScriptBlockByMessageId(this, "S00001");
                BindUserPercents();
                selectedvalue();
                }
            }
            catch (Exception ex)
            {
                string msgId = MessageUtility.LogAndGetMessageCode(ex);
                PageUtility.RegisterClientScriptBlockByMessageId(this, msgId);
            }
        }

        protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gridUserPercents.EditIndex = e.NewEditIndex;
            BindUserPercents();
            selectedvalue();
            List<String> list = new List<string>();
            list.Add("ACC");
            list.Add("APP");
            list.Add("ALL");
            DropDownList ddlCategoryE = (DropDownList)gridUserPercents.Rows[e.NewEditIndex].FindControl("gvddlCategory");
            ddlCategoryE.DataSource = list;
            ddlCategoryE.DataBind();
           
        }
        protected void gv_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gridUserPercents.EditIndex = -1;
            BindUserPercents();
            selectedvalue();
        }

        protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                string id = gridUserPercents.DataKeys[e.RowIndex].Values["ID"].ToString();
                TextBox txtFromDate = (TextBox)gridUserPercents.Rows[e.RowIndex].FindControl("gvtxtFromDate");
                TextBox txtEndDate = (TextBox)gridUserPercents.Rows[e.RowIndex].FindControl("gvtxtEndDate");
                DropDownList ddlCategory = (DropDownList)gridUserPercents.Rows[e.RowIndex].FindControl("gvddlCategory");
                TextBox txtUPercent = (TextBox)gridUserPercents.Rows[e.RowIndex].FindControl("gvtxtUPercent");
                TextBox txtComments = (TextBox)gridUserPercents.Rows[e.RowIndex].FindControl("gvtxtComments");
             DBHelper.Add("UpdateSPPercent", new object[] { 
                 int.Parse(id),
            txtFromDate.Text,
            txtEndDate.Text,
            "0."+txtUPercent.Text,
            txtComments.Text,
            ddlCategory.SelectedItem.ToString(),
            1,
            ddl1.SelectedValue.Split(',')[0].ToString()
            });
                PageUtility.RegisterClientScriptBlockByMessageId(this, "S00001");
                gridUserPercents.EditIndex = -1;
                BindUserPercents();
                selectedvalue();
                }
            catch (Exception ex)
            {
                string msgId = MessageUtility.LogAndGetMessageCode(ex);
                PageUtility.RegisterClientScriptBlockByMessageId(this, msgId);
            }


        }

        protected void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                string id = gridUserPercents.DataKeys[e.RowIndex].Values["ID"].ToString();
                DBHelper.Add("DeleteSPPercent", new object[] { 
                 int.Parse(id)
            });
                PageUtility.RegisterClientScriptBlockByMessageId(this, "S00001");
                
                BindUserPercents();
                selectedvalue();
            }
            catch (Exception ex)
            {
                string msgId = MessageUtility.LogAndGetMessageCode(ex);
                PageUtility.RegisterClientScriptBlockByMessageId(this, msgId);
            }
        }

        protected void gv_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridUserPercents.PageIndex = e.NewPageIndex;
            BindUserPercents();
            selectedvalue();
        }

        private void BindUserPercents()
        {
            DataSet dset = System.Utility.DBMS.DBHelper.GetDataTable("GetUsersPercent", new object[]{
            ddl1.SelectedValue.Split(',')[0].ToString(),
            ddlMonth.SelectedValue,
            ddlYear.SelectedValue
            }
                );
            if (dset.Tables[0].Rows.Count > 0)
            {
                gridUserPercents.DataSource = dset;
                gridUserPercents.DataBind();
                
            }
            else
            {
                dset.Tables[0].Rows.Add(dset.Tables[0].NewRow());
                gridUserPercents.DataSource = dset;
                gridUserPercents.DataBind();

                int gvcolumns = gridUserPercents.Columns.Count;
                gridUserPercents.Rows[0].Cells.Clear();
                gridUserPercents.Rows[0].Cells.Add(new TableCell());
                gridUserPercents.Rows[0].Cells[0].ColumnSpan = gvcolumns;

                gridUserPercents.Rows[0].Cells[0].Text = "No User Percents Found";
                gridUserPercents.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Red;
                gridUserPercents.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
                
            }


            DropDownList ddlCategory = (DropDownList)gridUserPercents.FooterRow.FindControl("ddlCategory");
            List<String> list = new List<string>();
            list.Add("ACC");
            list.Add("APP");
            list.Add("ALL");

            ddlCategory.DataSource = list;
            ddlCategory.DataBind();

        }

    }


}